package com.atguigu.mobileplayer2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.atguigu.mobileplayer2.domain.MediaItem;
import com.atguigu.mobileplayer2.utils.LogUtil;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ArrayList<MediaItem> mediaItems;
    private ArrayList<MediaItem> mediaItemMusic;
    String TAG= MainActivity.class.getName();
    int MY_PERMISSIONS_REQUEST_READ_CONTACTS= 128 ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 权限不同过

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
                Log.e(TAG,"用户点击一次权限拒绝，第二次申请，给用户一个提示");
                // 然后再次申请
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_CONTACTS);
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_CONTACTS);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }else{
            Log.e(TAG,"权限已经通过");
            readMovies();
            readAudios();
        }
    }

    public void goPlayPager(View view){

        int position= 0 ;
        MediaItem mediaItem = mediaItems.get(position);
//            Toast.makeText(context, "mediaItem=="+mediaItem.toString(), Toast.LENGTH_SHORT).show();

        //1.调起系统所有的播放-隐式意图，点击sd卡，图库视频，就是启动这个代码
        // 这里也可以放网络地址，如何搭建环境
        // 解压tomcat 把 yellow.mp4 放到 webapps/ROOT 下
        // 地址 : http://127.0.0.1:8080/yellow.mp4


            final String PLAYURL = "http://vfx.mtime.cn/Video/2014/03/05/mp4/140305150607196747_480.mp4";
            Intent intent = new Intent();
          //  intent.setDataAndType(Uri.parse("http://127.0.0.1:8080/yellow.mp4"),"video/*");
            intent.setDataAndType(Uri.parse(PLAYURL),"video/*");
          //  intent.setDataAndType(Uri.parse(mediaItem.getData()),"video/*");
            startActivity(intent);

        //2.调用自己写的播放器-显示意图--一个播放地址
//            Intent intent = new Intent(context,SystemVideoPlayer.class);
//            intent.setDataAndType(Uri.parse(mediaItem.getData()),"video/*");
//            context.startActivity(intent);


        //3.传递列表数据-对象-序列化
//        Intent intent = new Intent(MainActivity.this ,VitamioVideoPlayer.class);
//        Bundle bundle = new Bundle();
//        bundle.putSerializable("videolist",mediaItems);
//        intent.putExtras(bundle);
//        intent.putExtra("position",position);
//        startActivity(intent);
    }


    public void goPlayMusic(View view){
        int position= 10;
        //3.传递列表数据-对象-序列化
        Log.e(TAG,  mediaItemMusic.get(position).toString());
        Intent intent = new Intent(this,AudioPlayerActivity.class);
        intent.putExtra("position",position);
        startActivity(intent);
    }

    public void  readAudios(){
        mediaItemMusic = new ArrayList<>();
        ContentResolver resolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] objs = {
                MediaStore.Audio.Media.DISPLAY_NAME,//视频文件在sdcard的名称
                MediaStore.Audio.Media.DURATION,//视频总时长
                MediaStore.Audio.Media.SIZE,//视频的文件大小
                MediaStore.Audio.Media.DATA,//视频的绝对地址
                MediaStore.Audio.Media.ARTIST,//歌曲的演唱者

        };
        Cursor cursor = resolver.query(uri, objs, null, null, null);
        if(cursor != null){
            while (cursor.moveToNext()){
                MediaItem mediaItem = new MediaItem();
                mediaItemMusic.add(mediaItem);//写在上面
                String name = cursor.getString(0);//视频的名称
                mediaItem.setName(name);
                long duration = cursor.getLong(1);//视频的时长
                mediaItem.setDuration(duration);
                long size = cursor.getLong(2);//视频的文件大小
                mediaItem.setSize(size);
                String data = cursor.getString(3);//视频的播放地址
                mediaItem.setData(data);
                String artist = cursor.getString(4);//艺术家
                mediaItem.setArtist(artist);
            }
            cursor.close();
        }
        Log.e(TAG , "音频列表是： "  +   mediaItemMusic.toString());
        Log.e(TAG , "音频列表是： "  +   mediaItemMusic.size() );
    }

    public void  readMovies(){

        mediaItems = new ArrayList<>();
        ContentResolver resolver = getContentResolver();
        Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        String[] objs = {
                MediaStore.Video.Media.DISPLAY_NAME,//视频文件在sdcard的名称
                MediaStore.Video.Media.DURATION,//视频总时长
                MediaStore.Video.Media.SIZE,//视频的文件大小
                MediaStore.Video.Media.DATA,//视频的绝对地址
                MediaStore.Video.Media.ARTIST,//歌曲的演唱者

        };
        Cursor cursor = resolver.query(uri, objs, null, null, null);
        if(cursor != null){
            while (cursor.moveToNext()){
                MediaItem mediaItem = new MediaItem();
                mediaItems.add(mediaItem);//写在上面
                String name = cursor.getString(0);//视频的名称
                mediaItem.setName(name);
                long duration = cursor.getLong(1);//视频的时长
                mediaItem.setDuration(duration);
                long size = cursor.getLong(2);//视频的文件大小
                mediaItem.setSize(size);
                String data = cursor.getString(3);//视频的播放地址
                mediaItem.setData(data);
                String artist = cursor.getString(4);//艺术家
                mediaItem.setArtist(artist);
            }
            cursor.close();
        }
        Log.e(TAG , "视频列表是： "  +   mediaItems.toString());
        Log.e(TAG , "视频列表是： "  +   mediaItems.size() );
    }

    /**
     * 选中的位置
     */
    private int position;

    /**
     * 是否已经退出
     */
    private boolean isExit = false;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode ==KeyEvent.KEYCODE_BACK){
            if(position != 0){//不是第一页面, 回到第一个页
                position = 0;
               // rg_bottom_tag.check(R.id.rb_video);//首页
                return true;
            }else  if(!isExit){  //2S 内按2次退出
                isExit = true;
                Toast.makeText(MainActivity.this,"再按一次推出",Toast.LENGTH_SHORT).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isExit  = false;
                    }
                },2000);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

}